package zhoug.demo.zui.ui;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.widget.TextView;

import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Random;
import java.util.UUID;

import androidx.core.content.ContextCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import zhoug.common.http.SchedulerUtils;
import zhoug.common.utils.AppUtils;
import zhoug.common.utils.TimeUtils;
import zhoug.common.utils.ToastUtils;
import zhoug.demo.zui.BaseActivity;
import zhoug.demo.zui.R;
import zhoug.zui.ZUITopView;
import zhoug.zui.calendar.CalendarDay;
import zhoug.zui.calendar.OnCalendarListener;
import zhoug.zui.calendar.TagData;
import zhoug.zui.calendar.ZUICalendarView;
import zhoug.zui.dialog.ZUIButtonDialog;


/**
 * 自定义日历测试
 *
 * @Author: zhoug
 * @Date: 2024-01-26
 * @Description:
 */
public class CalendarViewActivity extends BaseActivity {
    private TextView mRightView;
    private boolean isEditing = false;

    private ZUITopView mTopView;
    private ZUICalendarView mCalendarView;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private int mStartPosition = -1;
    private int mEndPosition = -1;
    private String mCurrentId;


    @Override
    protected int getLayoutResId() {
        return R.layout.test_activity_calendar;
    }

    @Override
    protected void findViews() {
        mTopView = findViewById(R.id.topView);
        mCalendarView = findViewById(R.id.calendarView);
        mSwipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
    }

    @Override
    protected void init() {
        mRightView = mTopView.addRightTextView("编辑", View.generateViewId());
        mRightView.setOnClickListener(v -> {
            if (isEditing) {
                isEditing = false;
                mSwipeRefreshLayout.setEnabled(true);
                mRightView.setText("编辑");
                mCalendarView.showMonthBtn();
                mCalendarView.setDayItemClickable(false);
                mCalendarView.setLongTouchSelectable(false);
                ZUIButtonDialog buttonDialog=new ZUIButtonDialog(getActivity());
                buttonDialog.setTitle("提示");
                buttonDialog.setMessage("是否确定保存修改");
                buttonDialog.setNegativeListener("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        buttonDialog.dismiss();
                    }
                });
                buttonDialog.setPositiveListener("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        buttonDialog.dismiss();
//                        List<String> tabDate = mCalendarView.getTabDate();
//                        Logger.d(TAG, "tabDate:" + tabDate);
                        List<CalendarDay> days = mCalendarView.getDays();
                        for (CalendarDay item : days) {
                            item.setObject(null);
                            TagData tagData = item.getTagData();
                            if(tagData!=null){
                                tagData.setTabText("放假");
                                tagData.setBackground(null);
                            }
                        }
                        mCalendarView.notifyDataSetChanged();
                    }
                });
                buttonDialog.show();
            } else {
                isEditing = true;
                mSwipeRefreshLayout.setEnabled(false);
                mRightView.setText("确定");
                mCalendarView.hideMonthBtn();
                mCalendarView.setDayItemClickable(true);
                mCalendarView.setLongTouchSelectable(true);
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(this::loadData);
//        mSwipeRefreshLayout.setEnabled(false);
        mCalendarView.setTabType(ZUICalendarView.TAB_TYPE_TEXT);

        mCalendarView.setOnCalendarListener(new OnCalendarListener() {
            @Override
            public void onCalendarChange(int year, int month) {
                loadData();
            }

            /**
             * 获取日历标题
             *
             * @param showDay 当前是否展示日历内容
             * @param year    当前年
             * @param month   当前月
             * @param select  选中的天
             * @return
             */
            @Override
            public CharSequence getCalendarHeaderTitle(boolean showDay, int year, int month, CalendarDay select) {
                return null;
            }

            /**
             * 选中
             * @param calendarDay
             * @param calendarDay
             */
            @Override
            public void onSelectedChange(CalendarDay calendarDay) {
                ToastUtils.toastShort("选中:" + (calendarDay != null ? calendarDay.getDate() : ""));
            }

            /**
             * 取消选中
             * @param calendarDay
             * @param calendarDay
             */
            @Override
            public void onCancelSelected(CalendarDay calendarDay) {
                ToastUtils.toastShort("取消选中:" + (calendarDay != null ? calendarDay.getDate() : ""));

            }

            /**
             * 日期单击事件
             *
             * @param calendarDay
             * @param calendarDay
             */
            @Override
            public void onDayItemClick(CalendarDay calendarDay, int position) {
                ToastUtils.toastShort("单击:" + (calendarDay != null ? calendarDay.getDate() : ""));
                TagData tagData = calendarDay.getTagData();
                if (tagData != null) {
                    if(calendarDay.getObject()!=null){
                        calendarDay.setTagData(null);
                        mCalendarView.notifyItemChanged(position);
                    }else{
                        toast("历史数据不允许删除");
                    }
                } else {
                    tagData = new TagData(calendarDay.getDate());
                    tagData.setTabIcon(R.drawable.icon_jia);
                    tagData.setTabText("放假");
                    calendarDay.setTagData(tagData);
                    mCalendarView.notifyItemChanged(position);
                }
            }

            /**
             * 触摸位置的item
             *
             * @param calendarDay
             */
            @Override
            public void OnTouchDownPosition(CalendarDay calendarDay, int position) {
                mStartPosition = -1;
                mEndPosition = -1;
                mCurrentId= UUID.randomUUID().toString();
                if(ContextCompat.checkSelfPermission(CalendarViewActivity.this, Manifest.permission.VIBRATE)== PackageManager.PERMISSION_GRANTED){
                    AppUtils.vibrator(getActivity(), 200, 200);
                }
                if (position != -1) {
                    mStartPosition = position;
                    onTouchChange();
                }
            }

            @Override
            public void OnTouchMovePosition(CalendarDay calendarDay, int position) {
                if (position != -1) {
                    if (mStartPosition == -1) {
                        mStartPosition = position;
                    }
                    mEndPosition = position;
                    onTouchChange();
                }
            }

            @Override
            public void OnTouchUpPosition(CalendarDay calendarDay, int position) {
                if (position != -1) {
                    if (mStartPosition == -1) {
                        mStartPosition = position;
                    }
                    mEndPosition = position;
                    onTouchChange();
                }
            }
        });

        mCalendarView.setDate(2024, 3);
        loadData();
    }

    private void onTouchChange() {
        if (mStartPosition != -1 && mEndPosition != -1) {
            int startPos = mStartPosition;
            int endPos = mEndPosition;
            if (mStartPosition > mEndPosition) {
                startPos = mEndPosition;
                endPos = mStartPosition;
            }

            for (int i = 0; i < startPos; i++) {
                CalendarDay day = mCalendarView.getDay(i);
                if(Objects.equals(mCurrentId,day.getObject())){
                    day.setTagData(null);
                }
            }
            int dayCount = mCalendarView.getDayCount();
            int e=endPos+1;
            for (int i = e; i < dayCount; i++) {
                CalendarDay day = mCalendarView.getDay(i);
                if(Objects.equals(mCurrentId,day.getObject())){
                    day.setTagData(null);
                }
            }

            for (int i = startPos; i <= endPos; i++) {
                CalendarDay day = mCalendarView.getDay(i);
                TagData tagData = day.getTagData();
                if(tagData==null){
                    tagData=new TagData(day.getDate());
                    tagData.setTabText("新增");
                    day.setObject(mCurrentId);
                    tagData.setBackground(new ColorDrawable(Color.parseColor("#ff00ff")));
                    day.setTagData(tagData);
                }
            }
            mCalendarView.notifyDataSetChanged();
        }

    }

    private void loadData() {
        Observable
                .create((ObservableOnSubscribe<List<TagData>>) emitter -> {
                    Thread.sleep(200);
                    List<TagData> list = new ArrayList<>();
                    Random random = new SecureRandom();
                    ColorDrawable selected1 = new ColorDrawable(Color.parseColor("#99ff00ff"));
                    ColorDrawable normal1 = new ColorDrawable(Color.parseColor("#55ff00ff"));
                    ColorDrawable selected2 = new ColorDrawable(Color.parseColor("#99854952"));
                    ColorDrawable normal2 = new ColorDrawable(Color.parseColor("#55854952"));

                    String yearMonth = mCalendarView.getYearMonth();
                    String[] split = yearMonth.split("-");
                    Calendar calendar = Calendar.getInstance(Locale.CHINA);
                    calendar.set(Calendar.YEAR, Integer.parseInt(split[0]));
                    calendar.set(Calendar.MONTH, Integer.parseInt(split[1]) - 1);
                    calendar.set(Calendar.DAY_OF_MONTH, 1);

                    Date date = TimeUtils.addDay(calendar.getTime(), -1);
                    String date1 = TimeUtils.format(date, "yyyy-MM-dd");
                    TagData tagData = new TagData(date1);
                    tagData.setTabIcon(R.drawable.icon_jia);
                    tagData.setTabText("放假");
                    tagData.setObject(date1);
                    list.add(tagData);

                    for (int i = 1; i < 28; i++) {
                        if (random.nextBoolean()) {
                            String day = TimeUtils.addZero(String.valueOf(i));
                            tagData = new TagData(mCalendarView.getYearMonth()+"-"+day);
                            tagData.setTabIcon(R.drawable.icon_jia);
                            boolean b = random.nextBoolean();
                            tagData.setTabText("放假");
                            tagData.setObject(tagData.getDate());
                            list.add(tagData);
                        }
                    }
                    emitter.onNext(list);
                    emitter.onComplete();

                })
                .compose(SchedulerUtils.apply())
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this)))
                .subscribe(data -> {
                    if (data != null && data.size() > 0) {
                        mCalendarView.setSelect(data.get(data.size() - 1));
                    }
                    mCalendarView.setCalendarDay(data);
                    mSwipeRefreshLayout.setRefreshing(false);
                }, throwable -> {
                    toast(throwable.getMessage());
                });

    }


}
